package cn.itcast.jd.task;
import cn.itcast.jd.pojo.Item;
import cn.itcast.jd.service.ItemService;
import cn.itcast.jd.util.HttpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    private ItemService itemService;

    private static final ObjectMapper mapper =new ObjectMapper();


    //下载任务完成后，间隔多长时间进行下一次任务
    @Scheduled(fixedDelay = 100*1000)
    public void itemTask() throws Exception {

    //解析地址
    String url="https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&wq=%E6%89%8B%E6%9C%BA&pvid=efa025aae4ee4dda86806bee2561c6fa&s=116&click=0&page=";

       //遍历手机搜索的结果
        for (int i = 1; i < 20; i=i+2) {
            String html = httpUtils.doGetHtml(url + i);
            //解析页面，获取商品数量并存储
            this.parse(html);
        }
    }

    //解析页面，获取商品数据并存储
    private void parse(String html) throws Exception {
        //解析html获取document
        Document doc = Jsoup.parse(html);

        //获取spu信息
        Elements spuEls = doc.select("div#J_goodsList>ul>li");
        for (Element spuEl : spuEls) {
            //获取spu
//          long spu = Long.parseLong(spuEl.attr("data-spu"));
            String attr = spuEl.attr("data-spu");
            long spu = Long.parseLong(attr.equals("")?"0":attr);

            //获取sku信息
            Elements skuEles = spuEl.select("li.ps-item");
            for (Element skuEl : skuEles) {
                //获取sku
                long sku = Long.parseLong(skuEl.select("img[data-sku]").attr("data-sku"));

                //根据sku查询商品数量
                Item item = new Item();
                item.setSku(sku);
                List<Item> skuList = this.itemService.findAll(item);

                if (skuList.size() >0){
                    //如果商品存在，就进行下一个循环
                    continue;
                }
                //设置商品的spu
                item.setSpu(spu);

                //获取商品的详情的url
                String itemUrl ="https://item.jd.com/"+sku+".html";
                item.setUrl(itemUrl);

                //获取商品的图片
                String picUrl = "https:"+spuEl.select("img[data-sku]").first().attr("data-lazy-img");
                System.out.println(picUrl);

                //如果图片为空
                if (picUrl.equals("https:")){
                    break;
                }
                 picUrl = picUrl.replace("/n9/", "/n1/");//小换大
                String s = this.httpUtils.doGetImage(picUrl);
                item.setPicture(s);

//            //获取商品的价格
                String priceJson = this.httpUtils.doGetHtml("https://p.3.cn/prices/mgets?skuIds=J_" + sku);
                //多条数据取第一条
                double price = mapper.readTree(priceJson).get(0).get("p").asDouble();
                item.setPrice(price);

                //获取商品的标题
                String itemInfo = this.httpUtils.doGetHtml(item.getUrl());
                String title = Jsoup.parse(itemInfo).select("div#itemName").text();
                item.setTitle(title);

                item.setCreated(new Date());
                item.setUpdated(item.getCreated());
                //保存商品
                this.itemService.save(item);
            }
        }
    }
}
